<!-- Pdf 容器 -->
<template>
  <div id="pdfReader" class="grid w-screen-calc" ref="pdfReader">
    <div v-if="loading" class="col-12 justify-content-center align-items-center text-center">
      <ProgressBar :value="firstProgress"
                   mode="indeterminate"
                   style="height: .5em"></ProgressBar>
    </div>
    <ToolButton :top="50" v-if="loadData" :modal="false" @open="openHandler">
      <template #sidebarContent>
        <div id="catalogs" class="grid"></div>
      </template>
    </ToolButton>
    <!--    <div class="col-12 justify-content-center align-items-center text-center">
          <ProgressSpinner v-if="loading"
                           strokeWidth="8"
                           fill="var(&#45;&#45;surface-ground)"
                           animationDuration=".5s"/>
        </div>-->
    <!-- pdf -->
    <div id="preview"
         ref="preview"
         style="overflow:scroll;"
         class="pdf-preview col-12 justify-content-center align-items-center">
      <vue-pdf-embed class="vue-pdf-embed"
                     v-for="(page, index) in state.limit"
                     :id="`vue-pdf-page-${index}`"
                     :style="{'width': width/2+'px'}"
                     :source="state.source"
                     :page="page"
                     :key="index"/>
    </div>
    <!-- 可滚动加载条 -->
    <ProgressSpinner v-if="!loading && !loadData"
                     strokeWidth="8"
                     fill="var(--surface-ground)"
                     animationDuration=".5s"/>
  </div>

</template>

<script setup lang="ts">
/** JS */
import {ref, Ref, reactive, defineProps, onMounted, nextTick, watch, onUnmounted} from 'vue';
import {createLoadingTask} from "vue3-pdfjs/esm"; // 获得总页数
import Cache from '@/utils/Cache';
import axios from 'axios';
/** 组件 */
import ProgressBar from 'primevue/progressbar';
import ToolButton from '@/components/button/ToolButton.vue';
import ProgressSpinner from 'primevue/progressspinner';
import VuePdfEmbed from "vue-pdf-embed";


const preview = ref(null), pdfReader = ref(null);
const cache = new Cache();
const props = defineProps({
      url: {
        type: String,
        required: true
      }
    }), state = reactive({
      // 预览pdf文件地址
      source: '',
      //当前页面
      pageNum: 1,
      // 缩放比例
      scale: 1,
      // 总页数
      numPages: 0,
      // 动态高度
      height: 0,
      // 滚动分页
      limit: 2
    }),
    loading = ref(true),
    loadData = ref(false);

// 将文件访问一次后转地址流，避免消耗不必要的网络资源
axios({
  url: props.url,
  method: 'GET',
  responseType: 'arraybuffer'
}).then(res => {
  let blob = new Blob([res.data], {
    type: `application/pdf`,
  });
  let url = window.URL.createObjectURL(blob);
  state.source = url;
  const loadingTask = createLoadingTask(url);
  loadingTask.promise.then((pdf) => {
    state.numPages = pdf.numPages;
    loading.value = false;
  });
  cache.remove('temp_doc')

});

// 监听 canvas 数组
let canvasList: Ref<HTMLCanvasElement[]> = ref([]), firstCanvas: Ref<HTMLElement | null> = ref(null);
let canvasInterval = setInterval(() => {
  // 获取首个元素
  if (firstCanvas.value == null) {
    let first = document.getElementById('vue-pdf-page-0-1');
    if (first) {
      firstCanvas.value = first;
    }
  }
  // 获取目录
  if (state.numPages != 0 && canvasList.value.length == state.numPages) {
    // 如果 canvas 渲染完毕则执行该函数
    window.clearInterval(canvasInterval);
    return;
  } else if (state.numPages != 0) {
    for (let i = 0; i <= state.numPages; i++) {
      // 获取子元素
      let child = document.getElementById(`vue-pdf-page-${i}-${i + 1}`);
      if (child) {
        let tempDom = child.childNodes[0];
        if (tempDom && tempDom.nodeName == 'CANVAS') {
          // 覆盖确保顺序正确
          canvasList.value.splice(i, 1, (tempDom as HTMLCanvasElement));
          loadData.value = true;
        }
      }
    }
  }
}, 3000);
// 监听首次个 canvas 生成之后做滚动事件
let flag = true;
watch(firstCanvas, (n) => {
  nextTick(() => {
    if (n && flag) {
      let domHeight = n.clientHeight;
      let scrollHandler = (e) => {
        let doc = e.target.scrollingElement;
        if (doc) {
          let windowHeight = doc.clientHeight, scrollHeight = doc.scrollHeight, scrollTop = doc.scrollTop;
          if (Math.ceil(scrollTop + windowHeight) >= scrollHeight - (domHeight * 0.1) && state.limit < state.numPages) {
            state.limit += 1;
          }
        }
      };
      window.addEventListener('scroll', scrollHandler, true);
      flag = false;
    }
  })
});

let imgList: HTMLImageElement[] = [];
watch(canvasList, (n) => {
  if (n) {
    if (n.length > 0) {
      for (let i = 0; i < n.length; i++) {
        let sourceCanvas = n[i].toDataURL('image/png');
        let img = document.createElement('img');
        img.src = sourceCanvas;
        img.setAttribute('class', 'col-12 text-center');
        img.setAttribute('id', `vue-pdf-catalogs-${i}-${i + 1}`)
        img.style.height = '50%';
        img.classList.add('pdf-catalogs-item');
        img.onclick = function (i) {
          let id = (i.target as HTMLElement).getAttribute('id');
          if (id) {
            let pdfId = id.replace('vue-pdf-catalogs', 'vue-pdf-page');
            let pdfImg = document.getElementById(pdfId);
            if (pdfImg) {
              pdfImg.scrollIntoView({behavior: "smooth"});
            }
          }
        }
        // img.style.border = '1px solid';
        // img.style.marginTop = '20px';
        // img.style.boxShadow = '1px 1px 1px';
        // img.style.width = '50%';
        imgList.splice(i, 1, img);
      }
    }
  }
}, {deep: true})
const openHandler = (val) => {
  nextTick(() => {
    if (val) {
      let catalogs = document.getElementById('catalogs');
      if (catalogs) {
        for (let img of imgList) {
          catalogs.appendChild(img);
        }
      }
    }
  })
}
let width = ref(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth);
onMounted(() => {
  document.body.style.backgroundColor = 'rgb(66, 66, 66)';
});

// let startTime, endTime, tmpTime
// const next = () => {
//   if (state.pageNum < state.numPages) {
//     state.pageNum += 1;
//   }
// }, prev = () => {
//   if (state.pageNum > 1) {
//     state.pageNum -= 1;
//   }
// };
// const imgMouseHandler = (e, flag) => {
//   console.log('click ->' + state.source)
//   next();
//   if (e.button == 2) prev();
//   else if (flag) {
//     // 鼠标按下时开始获得 endTime
//     startTime = new Date().getTime();
//     tmpTime = setInterval(() => {
//       endTime = new Date().getTime();
//     })
//   } else {
//     console.log('up')
//     // 鼠标起来时，计算长按时间
//     if (endTime - startTime < 300) {
//       next();
//       if (tmpTime) clearInterval(tmpTime)
//     }
//   }
// }
// window.onscroll = function (e) {
//   if (preview.value) {
//     let dom = (preview.value as HTMLElement);
//     state.height = dom.scrollHeight;
//   }
// }


</script>

<style scoped>


.pdf-preview {
  position: relative;
  padding: 20px 0;
  box-sizing: border-box;
}

.vue-pdf-embed {
  margin: 20px auto;
  text-align: center;
  border: 1px solid #e5e5e5;
  box-sizing: border-box;
}
</style>
